package client.net.handler;

import client.Client;
import java.nio.ByteBuffer;
import shared.net.protocol.ServerHeader;

/**
 * This class handles various game end scenarios.
 * 
 * -- Game is over because a certain player won.
 * -- Game is over because a player disconnected.
 * -- Game is over because server is shutting down.
 * 
 * This class interrupts the UserIO thread.
 *
 * @author Vincent Tsuei
 * @version 2012-11-29
 */
public class GameEndHandler implements ClientPacketHandler {

    @Override
    public int processPacket(Client client, ByteBuffer packet) {
        if (!client.isPlaying()) { //Shouldn't happen.
            return -1;
        }
        
        byte normal = packet.get();
        byte winlose = packet.get();
        if (normal == 1) { //Normal win/lose situation
            if (winlose == 1) {
                client.getUserIO().write("You have won the match. Congrats!", true);
            } else if (winlose == 0) {
                client.getUserIO().write("You have lost the match. Sorry ...", true);
            } else {
                throw new RuntimeException("Unhandled packet structure - winlose - Game End Handler " + winlose);
            }
        } else if (normal == 0) {
            if (winlose == 1) {
                client.getUserIO().write("You have won the match because the opponent disconnected.", true);
            } else if (winlose == 0) {
                client.getUserIO().write("You have lost the match because you quit. ", true); 
                //Lul Wut. Will never happen. Might be useful if we add in forfeits.
            } else if (winlose == 2) {
                client.getUserIO().write("The game has been ended by the server. (It might be shutting down.)", true);
            } else {
                throw new RuntimeException("Unhandled packet structure - winlose - Game End Handler - " + winlose);
            }
        } else {
            //Unhandled
            throw new RuntimeException("Unhandled packet structure - normal - Game End Handler " + normal);
        }
        client.getGame().setOver();
        client.setLobby();
        client.interruptIOThread(false);
        if (client.getWaitResponseHeader() == ServerHeader.Send.GAME_UPDATE) {
            client.removeWaitForPacketFlag();
        }
        return 0;
    }
    
}
